package backed.controller;

import backed.dto.ChangePasswordRequest;
import backed.dto.GetMoneyRequest;
import backed.dto.LoginRequest;
import backed.dto.RegisterRequest;
import backed.entity.User;
import backed.service.UserService;
import backed.utils.JwtUtils;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Tag(name = "用户管理", description = "用户认证、注册、信息管理相关接口")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "通过账号和密码登录系统，返回用户信息和JWT Token", 
               security = @SecurityRequirement(name = ""))  // 登录接口不需要认证
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "登录成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "账号或密码错误")
    })
    public ResponseEntity<Map<String, Object>> login(@Valid @RequestBody LoginRequest request) {
        String account = request.getAccount();
        String password = request.getPassword();
        
        Map<String, Object> result = new HashMap<>();
        User user = userService.login(account, password);
        
        if (user != null) {
            // 生成JWT Token
            String token = jwtUtils.generateToken(user.getId());
            
            // 构建返回数据，包含用户信息和token
            // 为了兼容前端代码，在data顶层同时提供id和account
            Map<String, Object> data = new HashMap<>();
            data.put("user", user);
            data.put("token", token);
            data.put("id", user.getId());  // 在顶层添加id，方便前端直接访问
            data.put("account", user.getAccount());  // 在顶层添加account，方便前端直接访问
            
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("data", data);
            return ResponseEntity.ok(result);
        } else {
            result.put("success", false);
            result.put("message", "账号或密码错误");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }
    }
    
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "注册新用户账号，账号必须唯一",
               security = @SecurityRequirement(name = ""))  // 注册接口不需要认证
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "201", description = "注册成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "409", description = "账号已存在")
    })
    public ResponseEntity<Map<String, Object>> register(@Valid @RequestBody RegisterRequest request) {
        String account = request.getAccount();
        String password = request.getPassword();
        
        Map<String, Object> result = new HashMap<>();
        User user = userService.register(account, password);
        
        if (user != null) {
            result.put("success", true);
            result.put("message", "注册成功");
            result.put("data", user);
            return ResponseEntity.status(HttpStatus.CREATED).body(result);
        } else {
            result.put("success", false);
            result.put("message", "账号已存在");
            return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
        }
    }
    
    @GetMapping("/info")
    @Operation(summary = "获取用户信息", description = "根据用户ID获取用户详细信息")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public ResponseEntity<Map<String, Object>> getUserInfo(
            @Parameter(description = "用户ID", required = true, example = "1") @RequestParam Long id) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.getUserInfo(id);
        
        if (user != null) {
            result.put("success", true);
            result.put("data", user);
            return ResponseEntity.ok(result);
        } else {
            result.put("success", false);
            result.put("message", "用户不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
        }
    }
    @PutMapping("/update")
    @Operation(summary = "更新用户信息", description = "更新用户个人信息（昵称、头像、手机号等）")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "更新失败")
    })
    public ResponseEntity<Map<String, Object>> update(@RequestBody User updateUser) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否存在
        User user = userService.getUserInfo(updateUser.getId());
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
        }
        
        // 更新用户信息（更新非空字段）
        if (updateUser.getAccount() !=null) {
            user.setAccount(updateUser.getAccount());
        }
        if (updateUser.getNickname() != null) {
            user.setNickname(updateUser.getNickname());
        }
        if (updateUser.getAvatar() != null) {
            user.setAvatar(updateUser.getAvatar());
        }
        if (updateUser.getPhone() != null) {
            user.setPhone(updateUser.getPhone());
        }
        

        User savedUser = userService.update(user);
        
        if (savedUser != null) {
            result.put("success", true);
            result.put("message", "更新成功");
            result.put("data", savedUser);
            return ResponseEntity.ok(result);
        } else {
            result.put("success", false);
            result.put("message", "更新失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    /**
     * 修改密码接口
     * 需要提供原密码进行验证，验证通过后才能修改为新密码
     */
    @PostMapping("/change-password")
    @Operation(summary = "修改密码", description = "修改用户密码，需要提供原密码进行验证，新密码长度至少6位。请求参数示例：{\"userId\":1,\"oldPassword\":\"old123\",\"newPassword\":\"new123456\"}")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "密码修改成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误或新密码长度不足"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "原密码错误")
    })
    public ResponseEntity<Map<String, Object>> changePassword(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "修改密码请求参数",
                    required = true,
                    content = @Content(schema = @Schema(implementation = ChangePasswordRequest.class))
            )
            @Valid @RequestBody ChangePasswordRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        // 从DTO中获取参数
        Long userId = request.getUserId();
        String oldPassword = request.getOldPassword();
        String newPassword = request.getNewPassword();
        
        // 调用服务层修改密码
        boolean success = userService.changePassword(userId, oldPassword, newPassword);
        
        if (success) {
            result.put("success", true);
            result.put("message", "密码修改成功");
            return ResponseEntity.ok(result);
        } else {
            result.put("success", false);
            result.put("message", "原密码错误或用户不存在");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }
    }
    
    @GetMapping("/carbon-points")
    @Operation(summary = "查询碳积分", description = "根据用户ID查询碳积分和排名信息")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public ResponseEntity<Map<String, Object>> getCarbonPoints(
            @Parameter(description = "用户ID", required = true, example = "1") @RequestParam Long userId) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.getUserInfo(userId);
        
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
        }
        
        // 获取用户排名
        int ranking = userService.getUserRankByCarbonPoints(userId);
        
        Map<String, Object> data = new HashMap<>();
        data.put("userId", user.getId());
        data.put("carbonPoints", user.getCarbonPoints());
        data.put("ranking", ranking);
        
        result.put("success", true);
        result.put("data", data);
        return ResponseEntity.status(HttpStatus.OK).body(result);
    }
    @PostMapping("/getmoney")
    @Operation(summary = "获取资金", description = "根据用户ID获取指定金额的资金")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "获取成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不能为空"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "获取资金请求参数",
            required = true,
            content = @Content(schema = @Schema(implementation = GetMoneyRequest.class))
    )
    public ResponseEntity<Map<String, Object>> getmoney(
            @Valid @RequestBody GetMoneyRequest getMoneyRequest,
            HttpServletRequest request){
        Map<String,Object> result = new HashMap<>();
        
        Long userId = getMoneyRequest.getUserId();
        Double money = getMoneyRequest.getMoney();
        
        User user = userService.rqmoney(userId,money);
        if(user == null){
            result.put("success",false);
            result.put("message","用户不存在，userId: " + userId);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
        }
        Map<String,Object> data = new HashMap<>();
        data.put("money",money);
        data.put("userId",user.getId()); // 返回实际处理的用户ID
        data.put("requestUserId",userId); // 同时返回请求的用户ID用于对比
        data.put("total",user.getMoney());
        result.put("success",true);
        result.put("data",data);
        return ResponseEntity.ok(result);
    }




}
